<template>
	<view class="style-template-container">
		<!-- 筛选按钮区域 -->
		<view class="filter-section">
			<view 
				class="filter-wrapper"
				v-for="filter in filters"
				:key="filter.key"
			>
				<view 
					class="filter-btn"
					:class="{ active: activeFilter === filter.key }"
					@click="toggleDropdown(filter.key)"
				>
					<text class="filter-text">{{ getFilterDisplayName(filter) }}</text>
					<text class="filter-arrow" 
						:class="{ rotated: dropdownVisible === filter.key }"
						v-if="filter.hasDropdown">▼</text>
				</view>
				
				<!-- 下拉菜单 -->
				<view 
					class="dropdown-menu"
					:class="{ show: dropdownVisible === filter.key }"
					v-if="filter.hasDropdown"
				>
					<view 
						class="dropdown-item"
						:class="{ selected: isOptionSelected(filter.key, option.key) }"
						v-for="option in filter.options"
						:key="option.key"
						@click="selectOption(filter.key, option)"
					>
						<text class="dropdown-text">{{ option.name }}</text>
						<text class="check-icon" v-if="isOptionSelected(filter.key, option.key)">✓</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 点击背景关闭下拉菜单 -->
		<view class="overlay" v-if="dropdownVisible" @click="closeAllDropdowns"></view>
		
		<!-- 使用视频模板网格组件 -->
		<VideoTemplateGrid
			:templates="templates"
			:activeFilter="activeFilter"
			:networkType="networkType"
			:isWifiConnected="isWifiConnected"
			:autoPlayEnabled="autoPlayEnabled"
			@template-selected="handleTemplateSelected"
			@close-dropdowns="closeAllDropdowns"
			@video-play="handleVideoPlay"
			@video-pause="handleVideoPause"
			@filter-changed="handleFilterChanged"
			@auto-play-started="handleAutoPlayStarted"
			ref="templateGrid"
		/>
		

	</view>
</template>

<script>
// 导入视频模板网格组件
import VideoTemplateGrid from '@/components/ai-trip/VideoTemplateGrid.vue';

export default {
	components: {
		VideoTemplateGrid
	},
	data() {
		return {
			activeFilter: 'hot',
			selectedSubFilter: {}, // 存储每个主筛选项下的子选项
			dropdownVisible: '', // 当前显示的下拉菜单
			filters: [
				{ 
					key: 'hot', 
					name: '最热', 
					hasDropdown: true,
					options: [
						{ key: 'hot', name: '最热' },
						{ key: 'latest', name: '最新' }
					]
				},
				{ 
					key: 'romantic', 
					name: '浪漫', 
					hasDropdown: true,
					options: [
						{ key: 'romantic', name: '浪漫' },
						{ key: 'fresh', name: '清新' },
						{ key: 'energetic', name: '活力' }
					]
				},
				{ 
					key: 'gender', 
					name: '性别', 
					hasDropdown: true,
					options: [
						{ key: 'male', name: '男' },
						{ key: 'female', name: '女' }
					]
				},
				{ 
					key: 'scene', 
					name: '场景', 
					hasDropdown: true,
					options: [
						{ key: 'plant', name: '植物' },
						{ key: 'mountain', name: '山' },
						{ key: 'indoor', name: '室内' },
						{ key: 'sea', name: '海' }
					]
				}
			],
			
			// 小程序网络状态
			networkType: 'unknown',
			isWifiConnected: false,
			
			// 自动播放控制
			autoPlayEnabled: true, // 是否启用自动播放
			hasAutoPlayed: false, // 是否已经自动播放过
			
			templates: [
				{
					id: 1,
					title: '篮球运动换脸',
					author: '驴小拍',
					type: 'video',
					image: '', // 将通过video第一帧自动生成
					videoUrl: 'https://cdn.xryai.cn/picGo/20250906180807929.mp4',
					videoUrlLow: 'https://cdn.xryai.cn/picGo/20250906180807929.mp4',
					duration: '0:15',
					fileSize: '3.2MB',
					status: 'available',
					points: 10,
					category: 'romantic',
					gender: 'both',
					peopleCount: 1,
					priority: 1,
					projectId: 'at_1950826048993894400', // 腾讯云项目ID，待填写
					modelId: 'mt_1964264888492367872' // 腾讯云素材ID，待填写
				},
				{
					id: 2,
					title: '时尚风格·视频2',
					author: '驴小拍',
					type: 'video',
					image: '', // 将通过video第一帧自动生成
					videoUrl: 'https://cdn.xryai.cn/picGo/20250906180826132.mp4',
					videoUrlLow: 'https://cdn.xryai.cn/picGo/20250906180826132.mp4',
					duration: '0:20',
					fileSize: '4.1MB',
					status: 'available',
					points: 10,
					category: 'style',
					gender: 'both',
					peopleCount: 1,
					priority: 2,
					projectId: 'at_1950826048993894400', // 腾讯云项目ID，待填写
					modelId: 'mt_1964264947023880192' // 腾讯云素材ID，待填写
				}
			]
		}
	},

	
	async onLoad() {
		// 检测小程序网络状态
		await this.detectNetworkStatus();
		
		// 延迟自动播放第一个视频
		setTimeout(() => {
			this.startAutoPlay();
		}, 1000); // 延迟1秒，确保页面完全加载
	},
	
	onUnload() {
		// 清理网络监听
		uni.offNetworkStatusChange();
		
		// 清理内存监听
		if (uni.offMemoryWarning) {
			uni.offMemoryWarning();
		}
	},
	
	onHide() {
		// 页面隐藏时暂停所有视频
		if (this.$refs.templateGrid) {
			this.$refs.templateGrid.pauseAllVideos();
		}
	},
	
	onShow() {
		// 如果还没有自动播放过，延迟开始自动播放
		if (!this.hasAutoPlayed && this.autoPlayEnabled) {
			setTimeout(() => {
				this.startAutoPlay();
			}, 800);
		}
	},
	
	methods: {
		
		// 获取筛选器显示名称
		getFilterDisplayName(filter) {
			const selectedOption = this.selectedSubFilter[filter.key];
			if (selectedOption) {
				return selectedOption.name;
			}
			return filter.name;
		},
		
		// 切换下拉菜单显示状态
		toggleDropdown(filterKey) {
			if (this.dropdownVisible === filterKey) {
				this.dropdownVisible = '';
			} else {
				this.dropdownVisible = filterKey;
			}
		},
		
		// 选择下拉选项
		selectOption(filterKey, option) {
			this.selectedSubFilter[filterKey] = option;
			this.activeFilter = option.key;
			this.dropdownVisible = '';
			
			// 重置自动播放状态
			this.resetAutoPlayStatus();
			
			console.log('选择选项:', filterKey, option);
		},
		
		// 检查选项是否被选中
		isOptionSelected(filterKey, optionKey) {
			const selectedOption = this.selectedSubFilter[filterKey];
			return selectedOption && selectedOption.key === optionKey;
		},
		
		// 关闭所有下拉菜单
		closeAllDropdowns() {
			this.dropdownVisible = '';
		},
		
		// ========== 组件事件处理 ==========
		
		/**
		 * 处理模板选择事件
		 */
		handleTemplateSelected(template) {
			console.log('选择模板:', template);
			
			// 添加触觉反馈
			uni.vibrateShort({
				type: 'light'
			});
			
			// 选择当前网络环境下最适合的视频URL
			const selectedVideoUrl = this.selectVideoUrl(template);
			
			// 跳转到视频换脸详情页面，传递完整的模板信息
			const params = {
				modelId: template.modelId,
				title: encodeURIComponent(template.title),
				videoUrl: encodeURIComponent(selectedVideoUrl),
				templateId: template.id,
				duration: encodeURIComponent(template.duration || '0:15'),
				author: encodeURIComponent(template.author || '驴小拍'),
				// 传递原始URL和低质量URL，方便详情页根据网络切换
				originalUrl: encodeURIComponent(template.videoUrl),
				lowQualityUrl: encodeURIComponent(template.videoUrlLow || template.videoUrl)
			};
			
			const queryString = Object.entries(params)
				.map(([key, value]) => `${key}=${value}`)
				.join('&');
			
			console.log('[模板选择] 跳转参数:', params);
			
			uni.navigateTo({
				url: `/pages/ai-trip/ai_video/detail/index?${queryString}`
			});
		},
		
		/**
		 * 处理视频播放事件
		 */
		handleVideoPlay(templateId) {
			console.log('视频开始播放:', templateId);
			// 可以在这里添加播放统计等逻辑
		},
		
		/**
		 * 处理视频暂停事件
		 */
		handleVideoPause(templateId) {
			console.log('视频暂停:', templateId);
			// 可以在这里添加暂停统计等逻辑
		},
		
		/**
		 * 处理筛选条件变化事件
		 */
		handleFilterChanged() {
			// 重置自动播放状态
			this.resetAutoPlayStatus();
			
			// 延迟自动播放新筛选的第一个视频
			setTimeout(() => {
				this.startAutoPlay();
			}, 500);
		},
		
		/**
		 * 处理自动播放开始事件
		 */
		handleAutoPlayStarted(templateId) {
			this.hasAutoPlayed = true;
			console.log('自动播放开始:', templateId);
			
			// 自动播放成功提示 - 温和提示
			const template = this.templates.find(t => t.id === templateId);
			if (template) {
				setTimeout(() => {
					uni.showToast({
						title: `正在播放 ${template.title}`,
						icon: 'none',
						duration: 2000
					});
				}, 800); // 延迟显示，避免与页面加载冲突
			}
		},
		

		
		// ========== 辅助方法 ==========
		
		/**
		 * 根据网络选择视频URL
		 */
		selectVideoUrl(template) {
			// 2G/3G网络或非WiFi环境使用低质量
			if (this.networkType === '2g' || this.networkType === '3g' || 
				(!this.isWifiConnected && template.videoUrlLow)) {
				console.log(`[小程序质量] 选择低质量: ${template.title}`);
				return template.videoUrlLow;
			}
			
			return template.videoUrl;
		},
		
		/**
		 * 开始自动播放
		 */
		async startAutoPlay() {
			// 检查是否已经自动播放过
			if (this.hasAutoPlayed || !this.autoPlayEnabled) {
				return;
			}
			
			// 委托给组件处理
			if (this.$refs.templateGrid) {
				await this.$refs.templateGrid.startAutoPlay();
			}
		},
		
		/**
		 * 重置自动播放状态（用于筛选切换时）
		 */
		resetAutoPlayStatus() {
			this.hasAutoPlayed = false;
		},
		
		/**
		 * 检测小程序网络状态
		 */
		async detectNetworkStatus() {
			try {
				const networkInfo = await uni.getNetworkType();
				this.networkType = networkInfo.networkType;
				this.isWifiConnected = networkInfo.networkType === 'wifi';
				
				console.log(`[风格模板] 当前网络: ${this.networkType}`);
				
				// 监听网络状态变化
				uni.onNetworkStatusChange((res) => {
					this.networkType = res.networkType;
					this.isWifiConnected = res.networkType === 'wifi';
					console.log(`[风格模板] 网络变化: ${res.networkType}`);
					
					// 网络变化时重新调整策略
					this.adjustStrategyForNetwork();
				});
				
			} catch (error) {
				console.warn('[风格模板] 网络检测失败:', error);
			}
		}
	}
}
</script>

<style scoped>
.style-template-container {
	width: 100%;
	min-height: 100vh;
	background-color: #1a1a1a;
	color: #ffffff;
}

/* 筛选按钮区域 */
.filter-section {
	padding: 40rpx 60rpx 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	position: relative;
	background-color: #1a1a1a; /* 确保背景色一致 */
}

.filter-wrapper {
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.filter-btn {
	background-color: #2a2a2a;
	border-radius: 40rpx;
	padding: 20rpx 32rpx;
	display: flex;
	align-items: center;
	transition: all 0.3s ease;
	border: 2rpx solid transparent;
	position: relative;
	z-index: 10;
}

.filter-btn.active {
	background-color: #3a3a3a;
	border-color: #4a4a4a;
}

.filter-text {
	font-size: 28rpx;
	color: #ffffff;
	margin-right: 8rpx;
}

.filter-arrow {
	font-size: 20rpx;
	color: #888888;
	transition: transform 0.3s ease;
}

.filter-arrow.rotated {
	transform: rotate(180deg);
}

/* 下拉菜单样式 */
.dropdown-menu {
	position: absolute;
	top: 100%;
	left: 50%;
	transform: translateX(-50%);
	margin-top: 8rpx;
	background-color: #2a2a2a;
	border-radius: 16rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
	opacity: 0;
	visibility: hidden;
	transition: all 0.3s ease;
	min-width: 160rpx;
	z-index: 20;
	border: 1rpx solid #3a3a3a;
	white-space: nowrap;
}

.dropdown-menu.show {
	opacity: 1;
	visibility: visible;
	transform: translateX(-50%) translateY(0);
}

.dropdown-item {
	padding: 16rpx 24rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	transition: background-color 0.2s ease;
	border-bottom: 1rpx solid #3a3a3a;
	min-width: 120rpx;
}

.dropdown-item:last-child {
	border-bottom: none;
}

.dropdown-item:hover {
	background-color: #3a3a3a;
}

.dropdown-item.selected {
	background-color: #4a4a4a;
}

.dropdown-text {
	font-size: 26rpx;
	color: #ffffff;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.check-icon {
	font-size: 20rpx;
	color: #10b981;
	margin-left: 16rpx;
}

/* 背景遮罩 */
.overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 15;
	background: transparent;
}


/* 响应式设计 */
@media (max-width: 600rpx) {
	.filter-section {
		padding: 40rpx 30rpx 30rpx;
	}
	
	.filter-btn {
		padding: 16rpx 24rpx;
	}
	
	.filter-text {
		font-size: 26rpx;
	}
}


</style>
